package cs294s.liveradar.service;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import android.database.DataSetObserver;
import android.os.Handler;
import android.util.Log;

import cs294s.liveradar.data.Blip;
import cs294s.liveradar.data.Filter;

//A feed takes a filter and stores the blips for that feed.
public class Feed {

	ArrayList<Blip> blips = new ArrayList<Blip>();
	long latest_message_id = 0;
	Set<Long> ids_added = new HashSet<Long>();
	
	
	/**
	 * Used to post results back to the UI thread
	 */
	private Handler mHandler = new Handler();

	/**
	 * Observers interested in changes to the current list of feeds
	 */
	private ArrayList<WeakReference<DataSetObserver>> mObservers = 
		new ArrayList<WeakReference<DataSetObserver>>();

	
	private Filter filter;
	
	public Feed(Filter filter) {
		this.filter = filter;
	}
	
	public Handler getHandler() {
		return mHandler;
	}
	
	public String getId() {
		return filter.getId();
	}
	
	public int size() {
		return blips.size();
	}
	
	public Blip get(int position) {
		return blips.get(position);
	}
	
	public void clear() {
		blips.clear();   
		//notifyObservers();
	}
	
	/**
	 * Add an item to and notify observers of the change.
	 * @param item The item to add
	 */
	public void addBlip(Blip b) {
		long blip_id = b.getId();
		if(!ids_added.contains(blip_id)){
			ids_added.add(blip_id);
			if(blip_id > latest_message_id)
				latest_message_id = blip_id;
			Log.d("RADAR", "ADDED BLIP: " + blip_id + " TOTAL SIZE: " + size());
			
			if(filter.passFilter(b)) {
				b.setFilter(filter);
				blips.add(b);
			}
		}
	}
	
	public String[] getTagsArr() {
		return filter.tagsToStringArr();
	}
	
	public String getTags() {
		return filter.tagsToString();
	}
	
	public long getLatestMessageId() {
		return latest_message_id;
	}
	
	public String getName() {
		return filter.getName();
	}
	
	public String getDescription() {
		return filter.getDescription();
	}
	
}
